<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use App\Models\MPermissionRoles;
use App\Models\MRoles;
use App\Utils\MenuUtil;
use DB;
use http\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMenu()
    {
        $admin = Admin::find(ss('admin_id'));
        $data = [
            'code' => 0,
            'msg' => '获取成功！',
            'menu' => MenuUtil::adminCanMenus($admin)
        ];

        return $this->apiJson($data);
    }

    /**
     * @route   root/login-exit
     * @auth    安全管理
     * @desc    退出当前管理员的登陆
     */
    public function exitAct(Request $request)
    {
        $admin = Admin::find(ss('admin_id'));
        $admin->loginStatus(false);
        $this->data = $this->makeJsCode(0, '退出成功');
        return $this->apiJson();
    }

    /**
     * @route   root/auth/admins
     * @auth    安全管理
     * @desc    管理员列表
     */
    public function adminsPage(Request $request)
    {
        $query = (new Admin())->query();

        $search = $request->search;
        if (!empty($search)) {
            $query = $query->where('username', $request->search);
        }
        if ($request->type == 1) {
            //正序
            $query = $query->orderBy('id', 'desc');
        } elseif ($request->type == 2) {
            //倒序
            $query = $query->orderBy('id', 'asc');
        }
        $admins_obj = $query->where('super', 0)->get();
        if (empty($admins_obj)) {
            $this->data = $this->makeJsCode(1, "没有管理员");
            return $this->apiJson();
        }
        $admins = [];
        if ($admins_obj) {
            foreach ($admins_obj as $admin) {
                $array['id'] = $admin->id;
                $array['name'] = $admin->username;
                $array['role_name'] = $admin->roles->name;
                $array['last_ip'] = $admin->lastip;
                $array['login_time'] = $admin->lasttime ? date("Y-m-d H:i:s", $admin->lasttime) : '';
                array_push($admins, $array);
            }
        }

        $result = [
            "code" => 0,
            "msg" => "操作成功",
            "admins" => $admins,
        ];
        return $this->apiJson($result);
    }

    /**
     * @route   root/auth/admins-edit
     * @auth    安全管理
     * @desc    管理员编辑或添加页面
     * @param int $id 会员的id
     * @return
     */
    public function adminsEditPage(Request $request)
    {
        $admins = Admin::find($request->id);

        $roles = MRoles::all();
        $role_arr = [];
        if ($roles) {
            foreach ($roles as $role) {
                $arr['id'] = $role->id;
                $arr['name'] = $role->name;
                array_push($role_arr, $arr);
            }
        }

        $result = [];
        if (empty($admins)) {
            $result['code'] = 0;
            $result['msg'] = "操作成功";
            $result['name'] = "";
            $result['role_id'] = "";
            $result['role_list'] = $role_arr;
        } else {
            $result['code'] = 0;
            $result['msg'] = "操作成功";
            $result['name'] = $admins->username;
            $result['role_id'] = $admins->role_id;
            $result['role_list'] = $role_arr;
        }

        return $this->apiJson($result);
    }

    /**
     * @route   root/auth/admins-save
     * @auth    安全管理
     * @desc    管理员信息保存
     */
    public function adminsSave(Request $request)
    {

        if (!$this->validateReq($request, Admin::adminsSaveRulesWithMsg(0), Admin::adminsSaveRulesWithMsg(1))
        ) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return $this->apiJson();
        }

        if ($request->pass != $request->repass) {
            $this->data = $this->makeJsCode(1, "密码和确认密码不一致");
            return $this->apiJson();
        }
        //新添加管理员需检查管理员是否重名
        $admin = Admin::find($request->id);
        if (empty($admin)) {
            $admin = new Admin();
            if ($admin->existUserName($request->name)) {
                $this->data = $this->makeJsCode(1, "管理员名已经存在！");
                return $this->apiJson();
            }
        }
        try {
            DB::transaction(function () use ($request, $admin) {
                if ($admin->createOrSave_api($request)) {
                    $this->data = $this->makeJsCode(0, "保存管理员成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "保存管理员失败！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "保存管理员失败！");
        }
        return $this->apiJson();
    }


    /**
     * @route   root/auth/admins-del
     * @auth    安全管理
     * @desc    删除管理员
     */
    public function adminDel(Request $request)
    {
        $ids = json_decode($request->id, true);
        $admin = Admin::find($ids);
        if (!empty($admin)) {
            Admin::destroy($ids);
            $this->data = $this->makeJsCode(0, "删除成功！");

        } else {
            $this->data = $this->makeJsCode(1, "要删除的管理员不存在！");
        }
        return $this->apiJson();
    }

    /**
     * @route   root/auth/roles
     * @auth    安全管理
     * @desc    角色列表
     */
    public function roles(Request $request)
    {
        $roles = MRoles::all();
        if (empty($roles)) {
            $this->data = $this->makeJsCode(1, "操作失败!");
            return $this->apiJson();
        } else {
            $results = [];
            foreach ($roles as $value) {
                $this->date['id'] = $value['id'];
                $this->date['name'] = $value['name'];
                $this->date['description'] = $value['description'];
                $this->date['created_at'] = $value['created_at'] ? date("Y-m-d H:i:s", $value['created_at']) : '';
                $this->date['updated_at'] = $value['updated_at'] ? date("Y-m-d H:i:s", $value['updated_at']) : '';
                array_push($results, $this->date);
            }
            $this->data = $this->makeJsCode(0, "操作成功!");
            $this->data['roles'] = $results;
            return $this->apiJson();
        }
    }

    /**
     * @route   root/auth/roles-edit
     * @auth    安全管理
     * @desc    角色编辑页面
     */
    public function roles_edit(Request $request)
    {
        $id = $request->id;
        $date = MRoles::find($request->id);
        //为空时为添加   不为空是为编辑
        if (empty($date)) {
            //查出所有权限
            $result = MenuUtil::adminMenu();
            $array = [];
            foreach ($result as $value) {
                $res['id'] = $value['id'];
                $res['title'] = $value['title'];
                $res['checked'] = false;
                $goods = [];
                foreach ($value['child'] as $child) {
                    foreach ($child['child'] as $grandson) {
                        $data1['id'] = $grandson['id'];
                        $data1['title'] = $grandson['title'];
                        $data1['checked'] = false;
                        $goods[] = $data1;
                    }
                }
                $res['grandson'] = $goods;
                $array[] = $res;
            }
            return $this->apiJson(['code' => 0, 'msg' => '获取成功！', 'description' => '', 'all_pers' => $array]);
        } else {
            $permissions = MPermissionRoles::where('role_id', $request->id)->first();
            $permission = unserialize($permissions->permissions);
            //查出所有权限
            $result = MenuUtil::adminMenu();
            $array = [];
            foreach ($result as $value) {
                $id = $value['id'];
                $res['id'] = $value['id'];
                $res['title'] = $value['title'];
                $goods = [];
                foreach ($value['child'] as $child) {
                    foreach ($child['child'] as $grandson) {
                        $id = $grandson['id'];
                        $data1['id'] = $grandson['id'];
                        if (in_array($id, $permission)) {
                            $data1['checked'] = true;;
                            $res['checked'] = true;
                        } else {
                            $res['checked'] = false;
                            $data1['checked'] = false;
                        }
                        $data1['title'] = $grandson['title'];
                        $goods[] = $data1;
                    }
                }
                $res['grandson'] = $goods;
                $array[] = $res;
            }
            $des = MRoles::find($request->id);
            $id = $des->id;
            $name = $des->name;
            $description = $des->description;
            return $this->apiJson(['code' => 0, 'msg' => '获取成功！', 'id' => $id, 'name' => $name, 'description' => $description, 'all_pers' => $array]);
        }
    }

    /**
     * @route   root/auth/roles-save
     * @auth    安全管理
     * @desc    添加或编辑一个角色
     */
    public function roles_save(Request $request)
    {
        if (empty($request->name) && empty($request->permissions)) {
            $this->data = $this->makeJsCode(1, "请填写完整的角色数据！");
            return $this->apiJson();
        }

        //根据id判断角色存在不存在,存在时为编辑   不存在时为添加
        try {
            DB::transaction(function () use ($request) {
                if (MRoles::SaveOrCreateRole($request)) {
                    $this->data = $this->makeJsCode(0, "存储角色成功！");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "存储角色失败！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "操作失败！");
            return $this->apiJson();
        }
        return $this->apiJson();
    }

    /**
     * @route   root/auth/roles-del
     * @auth    安全管理
     * @desc    删除角色
     */
    public function roles_del(Request $request)
    {
        try {
            DB::transaction(function () use ($request) {
                $id_list = json_decode($request->id, true);
                $result = MRoles::find($id_list);
                if (!empty($result)) {
                    foreach ($id_list as $value) {
                        //检查当前角色下面是否还有管理员
                        $admins = Admin::all();
                        foreach ($admins as $admin) {
                            if ($admin->role_id == $value) {
                                $this->data = $this->makeJsCode(1, "此角色下还有管理员，不可以删除！");
                                return $this->apiJson();
                            }
                        }
                    }
                    if (MRoles::destroy($id_list)) {
                        MRoles::destroy($id_list);
                        $this->data = $this->makeJsCode(0, "删除角色成功！");
                    } else {
                        DB::rollBack();
                        $this->data = $this->makeJsCode(1, "删除角色失败！");
                    }
                } else {
                    $this->data = $this->makeJsCode(1, "要删除的角色不存在！");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode(1, "操作失败！");
        }
        return $this->apiJson();
    }
}
